import React, { useRef, useEffect } from 'react'
import * as echarts from 'echarts'

const axisOption = {
  // 图例文字颜色
  textStyle: {
    color: '#333'
  },
  // 提示框
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category', // 类目轴
    data: [] as string[],
    axisLine: {
      lineStyle: {
        color: '#17b3a3'
      }
    },
    axisLabel: {
      interval: 0,
      color: '#333'
    }
  },
  yAxis: [
    {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#17b3a3'
        }
      }
    }
  ],
  color: ['#2ec7c9', '#b6a2de', '#5ab1ef', '#ffb980', '#d87a80', '#8d98b3'],
  series: [
    {
      name: '',
      type: '',
      data: [] as number[] | { value: number; name: string }[]
    }
  ]
}

const normalOption = {
  tooltip: {
    trigger: 'item'
  },
  color: [
    '#0f78f4',
    '#dd536b',
    '#9462e5',
    '#a6a6a6',
    '#e1bb22',
    '#39c362',
    '#3ed1cf'
  ],
  series: [
    {
      name: '',
      type: '',
      data: [] as number[] | { value: number; name: string }[]
    }
  ]
}

interface EchartsProps {
  style: React.CSSProperties
  option: {
    xAxis?: string[]
    series: {
      name: string
      type: string
      data: number[] | { value: number; name: string }[]
    }[]
  }
  isAxisChart?: boolean
}

const Echarts: React.FC<EchartsProps> = ({
  style,
  option,
  isAxisChart = true
}) => {
  const echartRef = useRef(null)

  const echartsOp = useRef<echarts.EChartsType | null>(null)

  useEffect(() => {
    // ehcarts的实例化
    echartsOp.current = echarts.init(echartRef.current)
    let options
    // 设置options
    if (isAxisChart) {
      axisOption.xAxis.data = option.xAxis || []
      axisOption.series = option.series
      options = axisOption
    } else {
      normalOption.series = option.series
      options = normalOption
    }
    echartsOp.current.setOption(options)
  }, [option, isAxisChart])
  return <div style={style} ref={echartRef}></div>
}

export default Echarts
